/******************************************************************************
* Copyright (C) 2020 ShenZhen Powerdata Information Technology Co.,Ltd
* All Rights Reserved.
* 本软件为***研制。未经本公司正式书面同意，其他任何个人、团体不得使用、
* 复制、修改或发布本软件.
*****************************************************************************/

package com.xgf.common.xgfcommon.utils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
* @Title: 线程安全的map
* @ClassName:  MapConcurrentUtils   
* @Description:TODO  
* @author: xgf
* @date:   2020年2月8日 下午2:01:35   
* @since   JDK1.8
* @history 2020年2月8日 TODO 新建
*/
public class ConcurrentMapUtils {
	private ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<>();
	
	/**
	 *  统计list 出现次数  接受并发访问
	* @Title: add
	* @Description: TODO
	* @param @param key 
	* @return void
	* @throws
	 */
	public void add(String key) {
		synchronized (map) {
		AtomicInteger value = map.get(key);
		
		if(value == null) {
			value = new AtomicInteger();
			AtomicInteger old = map.putIfAbsent(key, value);
			//没放进去
			if(old != null) {
				
					value = old;
				
				
			}
		}
		value.incrementAndGet();
		}
	}
	
	public Integer getCount(String key) {
		return map.get(key).get();
	}
	
	public static void main(String[] args) {
		ConcurrentMapUtils concurrentMapUtils = new ConcurrentMapUtils();
		Thread thread = null;
			for (int i = 0; i < 1000; i++) {
				 thread = new Thread(new Runnable() {
					
					@Override
					public void run() {
						concurrentMapUtils.add("1");
					}
				});
				thread.start();
				
			}
			
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Integer count = concurrentMapUtils.getCount("1");
			System.out.println(count);
		
	}
	
	
	
}
